package com.mina.client;

import com.mina.constant.Constants;
import com.mina.model.Message;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

/**
 * 客户端
 */
public class Client {
    public static void main(String[] args) {
        // 1.创建连接
        NioSocketConnector connector = new NioSocketConnector();

        // 2.获取过滤器链
        getAndSetFilterChain(connector);

        // 4.设置客户端处理器
        connector.setHandler(new MinaClientHandler());
        connector.setConnectTimeoutMillis(10000);

        //5.连接服务器
        InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 9999);
        ConnectFuture cf = connector.connect(inetSocketAddress);
        ConnectFuture connectFuture = cf.awaitUninterruptibly();
        boolean connected = connectFuture.isConnected();
        Constants.session1 = cf.getSession();

        Scanner input = new Scanner(System.in);

        //以对象的方式传输数据
        CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 写
                    if (input.nextLine().equals("1")) {
                        cf.getSession().write(setMsg());
                    }
                }
            }
        });

        //等待服务器连接关闭，结束长连接
        cf.getSession().getCloseFuture().awaitUninterruptibly();
        connector.dispose();
    }

    /**
     * 获取并设置过滤器链
     *
     * @param connector c
     */
    private static void getAndSetFilterChain(NioSocketConnector connector) {
        DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();

        /* 设定过滤器规则，以对象为单位读取数据 */
        ObjectSerializationCodecFactory serializationCodecFactory = new ObjectSerializationCodecFactory();
        filterChain.addLast("logger", new LoggingFilter());
        filterChain.addLast("objectFilter", new ProtocolCodecFilter(serializationCodecFactory));
    }


    public static Message setMsg() {
        Message msg = new Message();
        msg.setFrom("client");
        msg.setTo("server");
        msg.setInfo("Hello, nice to meet you.");
        msg.setType("send");
        return msg;
    }

}